import os
import time

from django.template import loader

from apps.contents.models import ContentCategory
from meiduo_mall.settings import BASE_DIR
from utils.goods import get_categories


def generate_static_index_html():
    """
    生成静态的主页html文件
    """
    print('%s: generate_static_index_html' % time.ctime())

    # 获取商品频道和分类
    categories = get_categories()

    # 广告内容
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板
    context = {
        'categories': categories,
        'contents': contents
    }

    index_template = loader.get_template('index.html')
    index_html = index_template.render(context)

    store_path = os.path.join(os.path.dirname(BASE_DIR), 'front_end_pc', 'index.html')

    with open(store_path, 'w', encoding='utf-8') as fp:
        fp.write(index_html)
    print(f'store at {store_path}')
